public class Solution {
    /**
     * 删除链表的倒数第N个结点
     * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = nodeLength(head);
        int count = len - n;
        // System.out.println("count: " + count);
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode cur = newHead;
        while(count > 0) {
            //  System.out.println(cur.val);
            cur = cur.next;
            count--;
        }
        ListNode next = cur.next;
        if (next != null) {
            cur.next = next.next;
        }
        return newHead.next;
    }

    public int nodeLength(ListNode head) {
        ListNode cur = head;
        int n = 0;
        while(cur != null) {
            n++;
            cur = cur.next;
        }
        return n;
    }

    public void duplicateZeros(int[] arr) {
        // 找到需要复写的最后一个元素
        int slow = 0, fast = 0;
        int len = arr.length;
        while(fast < len - 1) {
            if (arr[slow] == 0) {
                fast++;
            }
            slow++;
            fast++;
        }
        System.out.println(slow);
        System.out.println(fast);
        // 从后向前进行复写(slow 为最后一个要复写的元素)
        // 若最后一位是0，0可能复写1次或两次，需要先特殊处理
        if (fast == len) {
            arr[len - 1] = 0;
            slow--;
            fast = len - 2;
        }

        while(slow >= 0) {
            if (arr[slow] != 0) {
                arr[fast--] = arr[slow--];
            } else {
                arr[fast--] = 0;
                arr[fast--] = 0;
                slow--;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {0, 0, 0, 0, 0, 0, 0};
        Solution solution = new Solution();
        solution.duplicateZeros(array);

        // Display the updated array after duplication
        for (int num : array) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }
